var editor = null;
$(document).ready(function () {
    var createCfgEditor = function () {
        require.config({paths:{'vs':'/js/monaco-editor/min/vs'}});
        require(['vs/editor/editor.main'], function() {
            editor = monaco.editor.create(document.getElementById("kernel-config"), {
                value: [].join('\n'),
                language: "cpp",
                automaticLayout: true,
                scrollBeyondLastLine: false
            });
        });

        if (editor) {
            editor.layout();
        }
    }

    createCfgEditor();

    function loadConfig() {
        $.getJSON("/api/admin/get-kernel-config", {}, function(json) {
            if (json.code !== 200) {
                return;
            }
            editor.setValue(json.data);
            editor.layout();
        },"json");
    }

    $(".kernel-config").click(function() {
        var scrollTop = window.pageYOffset||document.documentElement.scrollTop || document.body.scrollTop;
        var topPosInner = 60 + scrollTop;
        var leftPosIner = ($(document.body).width() - 1200)/2;
        document.getElementById('pop-inner-div-config').style.top= topPosInner +'px';
        document.getElementById('pop-inner-div-config').style.left= leftPosIner +'px';
        document.getElementById('pop-div-config').style.top= scrollTop +'px';
        document.documentElement.style.overflowY = 'hidden';

        $(".pop-div-config").fadeIn();
        $(".pop-inner-div-config").fadeIn();
        loadConfig()
        return false;
    });

    $(".pop-div-config").click(function(){
        $(".pop-div-config").fadeOut();
        $(".pop-inner-div-config").fadeOut();
        document.documentElement.style.overflowY = 'scroll';
    });

    var formSubmitListener = function () {
        postContent = function () {
            $(".fielderror").html("");
            $(".fieldsuccess").html("");
            var content = editor.getValue();
            $.post("/api/admin/save-kernel-config", { content: content },
                function (data) {
                    if (data.code != 200) {
                        $(".fielderror").html(data.msg);
                        return;
                    }

                    $('input[type=submit]', this).attr('disabled', 'disabled');
                    $(".fieldsuccess").html("save successfully.");
                },
                "json"
            );
        };
        postContent();
        return false;
    }
    $(".config-content-box").find("form").submit(formSubmitListener);
});